package com.geper.pattern.singleton;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: lsy
 * @date: 2020-02-27 15:36
 * @description: ContainerSingleton
 */
public class ContainerSingleton {

    //创建容器
    private static Map<String,Object> ioc = new ConcurrentHashMap<String, Object>();

    //这个地方虽然用了ConcurrentHashMap,但是只控制了map内部线程安全,线程不安全的是getBean()这个方法,ioc.put是线程安全的,所以在
    //getBean中添加synchronized关键字,保证线程安全,但是效率上会受到影响

    //构造私有化
    private ContainerSingleton(){}

    //全局访问点
    public static Object getBean(String className){
        synchronized (ioc){
            if (!ioc.containsKey(className)){
                Object obj = null;
                try {
                    obj = Class.forName(className).newInstance();
                    ioc.put(className,obj);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return obj;

            }
        }

        return ioc.get(className);
    }
}
